package com.simulate.core.servlet;

import com.simulate.core.annotation.*;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能描述: <br>
 * 所属包名: com.simulate.core.servlet<br>
 * 创建人　: 白剑<br>
 * 创建时间: 05/25/2018 21:35 Friday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
public class DispatcherServlet extends HttpServlet {

    private Properties applicationConfig = new Properties();

    private List<String> classNames = new LinkedList<>();

    private Map<String, Object> iocMap = new HashMap<>();

    private List<Handler> handerMapping = new LinkedList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        // 1. 加载配置文件
        doInitConfig(config.getInitParameter(""));

        // 2. 扫描所有相关的类
        doScanner(applicationConfig.getProperty("package.scan"));

        // 3. 实例化，把扫描到的类new出来（反射）, 并将其保存到ioc容器中
        doInstnace();

        // 4. 依赖注入DI，给刚刚new出来的类中的属性进行赋值
        doAutowired();

        // 5. 初始化HanderMapping
        initHanderMapping();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 6. HanderMapping 一个url对应一个method
        try {
            doDispatch(req, resp);
        } catch (IOException e) {
            resp.getWriter().write("500 Server Error：" + Arrays.toString(e.getStackTrace()));
            e.printStackTrace();
        }
    }

    private void doInitConfig(String initParameter) {
        InputStream inputStream = null;
        try {
            inputStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
            this.applicationConfig.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doScanner(String packageToScan) {
        String path = packageToScan.replaceAll("\\.", "/");
        URL url = this.getClass().getClassLoader().getResource("/" + path);
        File classDir = new File(url.getPath());
        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(packageToScan + "." + file.getName());
            } else {
                String className = packageToScan + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    private void doInstnace() {

        if (classNames.isEmpty()) {
            return;
        }

        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);

                // 只初始化带Controller和Service注解的类
                if (clazz.isAnnotationPresent(Controller.class)) {
                    String beanName = firstCharToLowerCase(clazz.getSimpleName());
                    iocMap.put(beanName, clazz.newInstance());
                } else if (clazz.isAnnotationPresent(Service.class)) {
                    Service service = clazz.getAnnotation(Service.class);
                    String beanName = service.value();
                    if (StringUtils.isBlank(beanName)) {
                        beanName = firstCharToLowerCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    iocMap.put(beanName, instance);

                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> i : interfaces) {
                        // TODO 没有考虑多个实现类的情况
                        iocMap.put(i.getName(), instance);
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doAutowired() {

        if (iocMap.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {

            // DI就是将ioc容器中存储的对象中加上了Autowired注解的字段实现自动赋值
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(Autowired.class)) {
                    continue;
                }

                Autowired autowired = field.getAnnotation(Autowired.class);
                String beanName = autowired.value();
                if (StringUtils.isBlank(beanName)) {
                    beanName = field.getType().getName();
                }

                field.setAccessible(true);

                try {
                    field.set(entry.getValue(), iocMap.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initHanderMapping() {

        if (iocMap.isEmpty()) {
            return;
        }

        // 只认controller
        System.out.println("-------------------------------------");
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {

            Class<?> clazz = entry.getValue().getClass();

            if (!clazz.isAnnotationPresent(Controller.class)) {
                continue;
            }

            // 类url+方法url组成完整访问url
            String baseUrl = "";
            if (clazz.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                baseUrl += requestMapping.value();
            }

            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                String regex = (baseUrl + requestMapping.value()).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                Handler handler = new Handler(pattern, entry.getValue(), method);
                handerMapping.add(handler);
                System.out.println("Mapping " + regex + " -> " + method);
            }
        }
        System.out.println("-------------------------------------");
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        // 等待请求

        Handler handler = getHandler(req);

        if (null == handler) {
            resp.getWriter().write("404 Not Found!");
            return;
        }

        // 获取方法的参数列表
        Class<?>[] paramTypes = handler.method.getParameterTypes();

        // 保存需要自动赋值的参数值
        Object[] paramValues = new Object[paramTypes.length];

        try {
            Map<String, String[]> params = req.getParameterMap();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String value = Arrays.toString(param.getValue()).
                        replaceAll("\\[|\\]", "").
                        replaceAll(",\\s", "");
                if (handler.paramIndexMapping.containsKey(param.getKey())) {
                    int index = handler.paramIndexMapping.get(param.getKey());
                    paramValues[index] = convert(paramTypes[index], value);
                }
            }

            // 设置方法中的requset和response
            if (handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())) {
                int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
                paramValues[reqIndex] = req;
            }
            if (handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())) {
                int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
                paramValues[respIndex] = resp;
            }

            handler.method.invoke(handler.controller, paramValues);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String firstCharToLowerCase(String name) {
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }

    private Handler getHandler(HttpServletRequest req) {

        if (handerMapping.isEmpty()) {
            return null;
        }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        for (Handler handler : handerMapping) {
            Matcher matcher = handler.pattern.matcher(url);
            if (matcher.matches()) {
                return handler;
            }
        }

        return null;
    }

    private Object convert(Class<?> type, String value) {
        if (Integer.class == type) {
            return Integer.valueOf(value);
        }
        return value;
    }

    private class Handler {

        private Object controller;
        private Method method;
        private Pattern pattern;
        private Map<String, Integer> paramIndexMapping;

        private Handler(Pattern pattern, Object controller, Method method) {
            this.pattern = pattern;
            this.controller = controller;
            this.method = method;

            paramIndexMapping = new HashMap<>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {

            // 提取方法中的注解参数
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for (int i = 0; i < parameterAnnotations.length; i++) {
                for (Annotation annotation : parameterAnnotations[i]) {
                    if (annotation instanceof RequestParam) {
                        String paramName = ((RequestParam) annotation).value();
                        paramIndexMapping.put(paramName, i);
                    }
                }
            }

            // 提取方法中的requset和response参数
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> type = parameterTypes[i];
                if (type == HttpServletRequest.class || type == HttpServletResponse.class) {
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }
    }

}
